package com.yingxue.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yingxue.demo.entity.Permission;
import com.yingxue.demo.mapper.PermissionMapper;
import com.yingxue.demo.service.PermissionService;
import com.yingxue.demo.util.ResultVOUtil;
import com.yingxue.demo.util.TreeUtil;
import com.yingxue.demo.vo.resp.PermissionTreeNodeRespVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Package: com.yingxue.demo.service.impl
 * @Author: Mr.Waves
 * @Date: 2020-03-31 18:15
 * @Description:
 **/
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public List<Permission> listAll() {
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 1);
        List<Permission> permissions = permissionMapper.selectList(queryWrapper);
        return permissions;
    }

    @Override
    public PermissionTreeNodeRespVO getPermissionTree() {
        // step1: 创建根节点root
        PermissionTreeNodeRespVO root = new PermissionTreeNodeRespVO();
        root.setTitle("默认顶级菜单");
        root.setId(0L);
        // step2: 获取菜单权限数据
        QueryWrapper<Permission> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 1).ne("type",3);
        List<Permission> permissions = permissionMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(permissions)) {
            return root;
        }
        // step3: 将实体封装成树节点
        List<PermissionTreeNodeRespVO> treeNodes = permissions.stream()
                .filter(permission -> !permission.getId().equals(permission.getPid()))
                .map(permission -> {
                    PermissionTreeNodeRespVO treeNode = new PermissionTreeNodeRespVO();
                    treeNode.setId(permission.getId());
                    treeNode.setPid(permission.getPid());
                    treeNode.setUrl(permission.getUrl());
                    treeNode.setTitle(permission.getName());
                    return treeNode;
                }).collect(Collectors.toList());

        // step4: 使用root和treeNodes建树
        return TreeUtil.build(treeNodes,root);
    }

}
